<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CCRM管理平台</title>
    <link rel="stylesheet" href="${gPath}/styles/dpl-min.css" />
    <link rel="stylesheet" href="${gPath}/styles/bui-min.css" />
    <link rel="stylesheet" href="${gPath}/styles/main.css" />
    <style type="text/css">
        input[type='radio']{
            width: 20px;
        }
        #deviceItems li{
            height: 20px;
            line-height: 20px;
        }
    </style>
</head>
<body>
    <%@include file="toolbar-header.jsp"%>
    <div class="container">
        <div id="chart" style="width: 1730px; height: 500px;"></div>
    </div>
    <div class="container">
        <form id="searchForm" class="form-panel">
            <div class="panel-content">
                <ul style="float: left;">
                    <li>
                        <span class="span3">活动选择：</span>
                        <div class="bui-form-group span15">
                            <select id="activitySelect">
                                <option value="">未选择</option>
                            </select>
                        </div>
                    </li>
                    <li>
                        <span class="span3">设备集合：</span>
                        <div class="bui-form-group span15">
                            <div id="deviceItems">
                                <input id="deviceIds" name="deviceIds" type="hidden"/>
                                <div hidefocus="true" tabindex="0" style="width: 500px;" class="bui-combox bui-select">
                                    <div class="bui-simple-list">
                                        <ul id="ul">
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <input type="text" placeholder="输入ID" onblur="addItem(this)" onkeydown="addItemWithKey(this,event)"/>
                        </div>
                    </li>
                </ul>
                <ul style="float: left;">
                    <li>
                        <span class="span3">起止时间：</span>
                        <div class="bui-form-group span15" data-rules="{dateRange : true}">
                            <input id="startTime" name="startTime" class="Wdate" type="text" readonly="true"/>
                            <label>&nbsp;&nbsp;~&nbsp;&nbsp;</label>
                            <input id="endTime" name="endTime" class="Wdate" type="text" readonly="true"/>
                        </div>
                    </li>
                    <li>
                        <span class="span3">统计周期：</span>
                        <div class="bui-form-group span15">
                            <input type="radio" name="timeType" value="year"/>年&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="timeType" value="quarter"/>季度&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="timeType" value="month" checked="true"/>月&emsp;&emsp;&emsp;&emsp;
                        </div>
                    </li>
                    <li>
                        <span class="span3">&emsp;&emsp;&emsp;&emsp;</span>
                        <div class="bui-form-group span15">
                            <input type="radio" name="timeType" value="week"/>周&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="timeType" value="day"/>日&emsp;&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="timeType" value="hour"/>时&emsp;&emsp;&emsp;&emsp;
                        </div>
                    </li>
                    <li>
                        <span class="span3">展示方式：</span>
                        <div class="bui-form-group span15">
                            <input type="radio" name="showType" value="line" checked="true"/>折线图&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="showType" value="column"/>柱状图&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="showType" value="pie"/>饼图&emsp;&emsp;&emsp;&emsp;
                            <input type="radio" name="showType" value="map"/>地域分布&emsp;&emsp;&emsp;&emsp;
                        </div>
                    </li>
                    <li>
                        <div class="bui-form-group span15">
                            <button type="button" class="button button-primary" onclick="loadChart()">确定</button>
                        </div>
                    </li>
                </ul>
                <div style="clear:both;"></div>
            </div>
        </form>
    </div>

    <script type="text/javascript" src="${gPath}/scripts/jquery/jquery-1.8.1.min.js"></script>
    <script type="text/javascript" src="${gPath}/scripts/bui.js"></script>
    <script type="text/javascript" src="${gPath}/scripts/seed-min.js"></script>
    <script type="text/javascript" src="${gPath}/scripts/acharts.js"></script>
    <script type="text/javascript" src="${gPath}/scripts/echarts-all.js"></script>
    <script type="text/javascript" src="${gPath}/scripts/My97DatePicker/WdatePicker.js"></script>
    <script type="text/javascript">
    var format = "yyyy-MM";
    var lastItemValue = null;
    var chartData = null;

    $(function(){
        var wdate = $(".Wdate");
        var date = new Date();
        wdate.val(BUI.Date.format(date, "yyyy-mm", null));
        wdate.focus(function(){
            WdatePicker({dateFmt:format, maxDate:'%y-%M-%d'});
        });

        //加载图表数据
        loadChart();

        var chart = $("#chart");
        var width = chart.parent().css("width");
        chart.css("width", width);
        //图表Div动态改变大小，Map组件需要该Div有width和height属性。
        $(window).bind("resize", function(){
            var width = chart.parent().css("width");
            chart.css("width", width);
        });

        $("input[type='radio'][name='timeType']").click(function(){
            if (this.checked){
                switch (this.value){
                    case "year":
                        if (lastItemValue != "year"){
                            format = "yyyy";
                            wdate.val(BUI.Date.format(date, format, null));
                        }
                        break;
                    case "quarter":
                    case "month":
                        if (lastItemValue != "quarter" && lastItemValue != "month"){
                            format = "yyyy-MM";
                            wdate.val(BUI.Date.format(date, "yyyy-mm", null));
                        }
                        break;
                    case "week":
                    case "day":
                    case "hour":
                        if (lastItemValue != "week" && lastItemValue != "day" && lastItemValue != "hour"){
                            format = "yyyy-MM-dd";
                            wdate.val(BUI.Date.format(date, "yyyy-mm-dd", null));
                        }
                        break;
                }
                lastItemValue = this.value;
            }
        });

        $("input[type='radio'][name='showType']").click(function(){
            if (this.checked){
                changeShowType(this.value, chartData);
            }
        });

        $("#activitySelect").change(function(){
            var deviceIds = $("#deviceIds");
            deviceIds.val(null);
            $("#ul").empty();
            if (this.value != ""){
                var currEle = this;
                $.getJSON("${gPath}/clmp/deviceTag/getDevices", {"deviceTag.id": this.value}, function(data){
                    var ids = "";
                    var ul = $("#ul");
                    for (var i in data){
                        ul.append('<li class="bui-list-item">'+ data[i].device_id +'<button onclick="removeItem(this)">×</button></li>');
                        ids += (i == 0 ? data[i].device_id : ","+ data[i].device_id);
                    }
                    deviceIds.val(ids);

                    var currOption = $(currEle.options[currEle.selectedIndex]);
                    $("#startTime").val(currOption.attr("starttime").split(" ")[0]);
                    $("#endTime").val(currOption.attr("endtime").split(" ")[0]);
                    $("input[type='radio'][name='timeType']").eq(4).attr("checked", true);
                    lastItemValue = "day";
                    format = "yyyy-MM-dd";
                });
            }
        });

        $.getJSON("${gPath}/clmp/deviceTag/getAll", function(data){
            var activitySelect = $("#activitySelect");
            for (var i in data)
                activitySelect.append("<option value='"+ data[i].id +"' starttime='"+ data[i].start_time +"' endtime='"+ data[i].end_time +"'>"+ data[i].tag_name +"</option>");
        });
    });

    function removeItem(obj){
        var li = $(obj).parent("li");
        var deviceIds = $("#deviceIds");
        var tempIds = deviceIds.val().split(",");
        tempIds.splice(tempIds.indexOf(li.contents().eq(0).text()), 1);
        deviceIds.val(tempIds.length == 0 ? null : tempIds.join());
        li.remove();
    }

    function addItem(obj){
        var deviceId = obj.value.trim();
        if (deviceId != ""){
            if (!/^\d+$/.test(deviceId)){
                BUI.Message.Alert('设备ID必须是数字！');
                return;
            }
            var deviceIds = $("#deviceIds");
            var idsArr = deviceIds.val().split(",");
            if (idsArr[idsArr.length - 1] != deviceId){
                $.getJSON("${gPath}/clmp/device/getById", {deviceId: deviceId}, function(data){
                    if ($.isEmptyObject(data)){
                        BUI.Message.Alert('设备不存在！');
                    } else {
                        $("#ul").append('<li class="bui-list-item">'+deviceId+'<button onclick="removeItem(this)">×</button></li>');
                        deviceIds.val(deviceIds.val() != "" ? deviceIds.val() +","+ deviceId : deviceId);
                    }
                });
            }
        }
        obj.value = null;
    }

    function addItemWithKey(obj, e){
        if (e.keyCode == 13)
            $(obj).blur();
    }

    //加载图表数据
    function loadChart(){
        var showType = $("input[type='radio'][name='showType']:checked").val();
        if (showType != "map"){
            var params = $("#searchForm").serialize();
            $.getJSON("${gPath}/clmp/dingtalk/pc/sumBrewed", params, function(data){
                chartData = optimizeChartData(data);
                changeShowType(showType, chartData);
            });
        } else {
            changeShowType(showType);
        }
    }

    //优化图表空参数防止卡死
    function optimizeChartData(chartData){
        if (chartData.date.length == 0)
            chartData.date = ["-"];
        if (chartData.app.length == 0)
            chartData.app = [0];
        if (chartData.local.length == 0)
            chartData.local = [0];
        return chartData;
    }

    function changeShowType(showType, data){
        if (mapChart != null){
            mapChart.clear();
            mapChart.dispose();
            mapChart = null;
        }
        switch (showType){
            case "line": renderLineChart(data); break;
            case "column": renderColumnChart(data); break;
            case "pie": renderPieChart(data); break;
            case "map": renderMap(); break;
        }
    }

    //渲染折线图
    function renderLineChart(option){
        $('#chart').empty();
        var chart = new AChart({
            theme : AChart.Theme.SmoothBase,
            id : "chart",
            forceFit : true,
            width : 950,
            height : 500,
            plotCfg : {
                margin : [50,50,80] //画板的边距
            },
            title : {
                text : "该时段冲泡"+(option.sumApp + option.sumLocal)+"次(APP "+ option.sumApp +"次/本机 "+option.sumLocal+"次)"
            },
            subTitle : {
                text : "累计冲泡次数("+ option.sumAll +"次)"
            },
            xAxis : {
                categories: option.date
            },
            yAxis : {
                title : "次数",
                rotate : -90
            },
            seriesOptions : { //设置多个序列共同的属性
                lineCfg : { //不同类型的图对应不同的共用属性，lineCfg,areaCfg,columnCfg等，type + Cfg 标示
                    smooth : true,
                    labels : { //标示显示文本
                        label : { //文本样式
                            y : -15
                        }
                    }
                }
            },
            tooltip : {
                valueSuffix : "次",
                shared : true, //是否多个数据序列共同显示信息
                crosshairs : true //是否出现基准线
            },
            series : [{
                name: 'APP冲泡',
                data: option.app
            }, {
                name: '本机冲泡',
                data: option.local
            }]
        });
        chart.render();
    }

    //渲染柱状图
    function renderColumnChart(option){
        $('#chart').empty();
        chart = new AChart({
            theme : AChart.Theme.SmoothBase,
            id : 'chart',
            forceFit : true,
            width : 950,
            height : 500,
            xAxis : {
                categories: option.date
            },
            yAxis : {
                title : "次数",
                rotate : -90,
                min : 0
            },
            title : {
                text : "该时段冲泡"+(option.sumApp + option.sumLocal)+"次(APP "+ option.sumApp +"次/本机 "+option.sumLocal+"次)"
            },
            subTitle : {
                text : "累计冲泡次数("+ option.sumAll +"次)"
            },
            tooltip : {
                valueSuffix : "次",
                shared : true
            },
            seriesOptions : {
                columnCfg : {
                    stackType: 'normal'
                }
            },
            series: [{
                name: 'APP冲泡',
                data: option.app
            }, {
                name: '本机冲泡',
                data: option.local
            }]
        });
        chart.render();
    }

    //渲染饼图
    function renderPieChart(option){
        /******************************处理数据****************************/
        var appDataArr = [];
        var localDataArr = [];
        for (var i in option.date){
            if (option.app[i] > 0)
                appDataArr.push([option.date[i], option.app[i]]);
            if (option.local[i] > 0)
                localDataArr.push([option.date[i], option.local[i]]);
        }
        /******************************处理数据****************************/
        var chartDiv = $('#chart');
        chartDiv.empty();
        chartDiv.append("<div id='chart1' style='float: left;width: 50%;'></div><div id='chart2' style='float: left;width: 50%;'></div>");
        if (appDataArr.length == 0){
            $("#chart1").append('<div style="padding: 20px" class="centered"><img alt="Crying" src="${gPath}/img/nodata.png" style="height: 450px;"><h2>APP冲泡还没有数据</h2></div>');
        } else {
            var chart = new AChart({
                theme : AChart.Theme.SmoothBase,
                id : 'chart1',
                width : 600,
                height : 500,
                plotCfg : {
                    margin : [100,80,80] //画板的边距
                },
                title : {
                    text : "该时段APP冲泡"+ option.sumApp +"次"
                },
                legend : null ,//不显示图例
                seriesOptions : { //设置多个序列共同的属性
                    pieCfg : {
                        allowPointSelect : true,
                        labels : {
                            distance : 40,
                            label : {
                                //文本信息可以在此配置
                            },
                            renderer : function(value,item){ //格式化文本
                                return value + ' ' + (item.point.percent * 100).toFixed(2)  + '%('+item.point.value+'次)';
                            }
                        }
                    }
                },
                tooltip : {
                    pointRenderer : function(point){
                        return (point.percent * 100).toFixed(2)+ '%';
                    }
                },
                series : [{
                    type: 'pie',
                    name: 'APP冲泡百分比',
                    data: appDataArr
                }]
            });
            chart.render();
        }

        if (localDataArr.length == 0){
            $("#chart2").append('<div style="padding: 20px" class="centered"><img alt="Crying" src="${gPath}/img/nodata.png" style="height: 450px;"><h2>本机冲泡还没有数据</h2></div>');
        } else {
            var chart = new AChart({
                theme : AChart.Theme.SmoothBase,
                id : 'chart2',
                width : 600,
                height : 500,
                plotCfg : {
                    margin : [100,80,80] //画板的边距
                },
                title : {
                    text : "该时段本机冲泡"+ option.sumLocal +"次"
                },
                legend : null ,//不显示图例
                seriesOptions : { //设置多个序列共同的属性
                    pieCfg : {
                        allowPointSelect : true,
                        labels : {
                            distance : 40,
                            label : {
                                //文本信息可以在此配置
                            },
                            renderer : function(value,item){ //格式化文本
                                return value + ' ' + (item.point.percent * 100).toFixed(2)  + '%('+item.point.value+'次)';
                            }
                        }
                    }
                },
                tooltip : {
                    pointRenderer : function(point){
                        return (point.percent * 100).toFixed(2)+ '%';
                    }
                },
                series : [{
                    type: 'pie',
                    name: '本机冲泡百分比',
                    data: localDataArr
                }]
            });
            chart.render();
        }
    }

    var mapChart = null;
    var option = {
        title : {
            text: '冲泡分布',
            x:'center'
        },
        tooltip : {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            x:'left',
            data:['冲泡分布']
        },
        dataRange: {
            show: true,
            min: 0,
            max: 100,
            x: 'left',
            y: 'bottom',
            text:['高','低'],
            calculable : true
        },
        toolbox: {
            show: true,
            orient : 'vertical',
            x: 'right',
            y: 'center',
            feature : {
                dataView : {
                    show: true,
                    readOnly: true,
                    optionToContent: function(opt) {
                        var sum = 0;
                        var tempDatas = opt.series[0].data;
                        var table = '<table style="width:100%;text-align:center"><tbody><tr><td>地区</td><td>次数</td></tr>';
                        for (var i in tempDatas) {
                            table += '<tr><td>' + tempDatas[i].name + '</td><td>' + tempDatas[i].value + '</td></tr>';
                            sum += parseInt(tempDatas[i].value);
                        }
                        table += '<tr><td><h3 style="color: #ff0000">合计</h3></td><td><h3 style="color: #ff0000">'+ sum +'</h3></td></tr>';
                        table += '</tbody></table>';
                        return table;
                    }
                },
                restore : {show: true, title : '还原'},
                saveAsImage : {show: true, title : '保存为图片'}
            }
        },
        series:[{
            name: '冲泡数',
            type: 'map',
            mapType: 'china',
            roam: true,
            itemStyle:{
                normal:{label:{show:true}},
                emphasis:{label:{show:true}}
            },
            data: []
        }]
    };

    function renderMap(){
        $("#chart").empty();
        mapChart = echarts.init(document.getElementById('chart'));
        window.onresize = mapChart.resize;

        var params = $("#searchForm").serialize();
        $.getJSON("${gPath}/clmp/dingtalk/pc/sumBrewed/sumByMap", params, function(data){
            var max = 100;
            for (var i in data){
                var value = parseInt(data[i].value);
                if (value > max)
                    max = value;
                data[i].name = data[i].name.replace(/市|省/g, "");
            }
            option.series[0].data = data;
            option.dataRange.max = getMaxIntRange(max);
            mapChart.setOption(option);
        });
    }

    /**
     * 处理地图范围最大值为整数
     */
    function getMaxIntRange(num){
        var numStr = new String(num);
        if (/^[1-9][0]*$/.test(numStr)){
            return num;
        }

        var first = parseInt(numStr.charAt(0)) + 1;
        var result = first;
        for (var i = 0; i < numStr.length - 1; i++){
            result += "0"
        }
        return parseInt(result);
    }
    </script>
</body>
</html>